#include <linux/fs.h>
#include <linux/module.h>
#include "ntfs_kernel.h"

static int ntfs_fill_super(struct super_block *sb, void *data, int silent) {
    struct ntfs_volume *vol;
    struct buffer_head *bh;
    int flags = SB_RDONLY;

    /* 获取设备路径 */
    const char *dev_name = data;
    sb->s_bdev = blkdev_get_by_path(dev_name, FMODE_READ | FMODE_WRITE, NULL);
    if (IS_ERR(sb->s_bdev)) {
        printk(KERN_ERR "NTFS: Failed to open block device\n");
        return PTR_ERR(sb->s_bdev);
    }

    /* 初始化NTFS卷 */
    vol = ntfs_mount(sb->s_bdev->bd_dev, NTFS_DEFAULT_OPTIONS);
    if (IS_ERR(vol)) {
        printk(KERN_ERR "NTFS: Volume mount failed\n");
        return PTR_ERR(vol);
    }

    /* 检查脏标志 */
    if (vol->flags & VOLUME_IS_DIRTY) {
        printk(KERN_WARNING "NTFS: Dirty volume detected, force readonly\n");
        flags |= MS_RDONLY;
    }

    sb->s_flags = flags;
    sb->s_fs_info = vol;
    sb->s_op = &ntfs_super_ops;
    return 0;
}

static struct dentry *ntfs_mount(struct file_system_type *fs_type,
        int flags, const char *dev_name, void *data) {
    return mount_bdev(fs_type, flags, dev_name, data, ntfs_fill_super);
}

static void ntfs_kill_sb(struct super_block *sb) {
    struct ntfs_volume *vol = sb->s_fs_info;
    if (vol) {
        ntfs_umount(vol, 1);
        sb->s_fs_info = NULL;
    }
    kill_block_super(sb);
}

/* VFS注册结构体 */
static struct file_system_type ntfs_fs_type = {
    .owner      = THIS_MODULE,
    .name       = "ntfs",
    .mount      = ntfs_mount,
    .kill_sb    = ntfs_kill_sb,
    .fs_flags   = FS_REQUIRES_DEV,
};

/* 内核模块初始化 */
static int __init ntfs_init(void) {
    int ret = register_filesystem(&ntfs_fs_type);
    if (ret)
        printk(KERN_ERR "NTFS registration failed: %d\n", ret);
    return ret;
}

LOS_MODULE_INIT(ntfs_init, LOS_INIT_LEVEL_KMOD_EXTENDED);

